import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

# 均值滤波
def blur(source):
    img = cv2.blur(source, (10, 10))
    cv2img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    pillowimg = Image.fromarray(cv2img)
    draw = ImageDraw.Draw(pillowimg)  # 图像上打印
    font = ImageFont.truetype("simhei.ttf", 20, encoding="utf-8")
    draw.text((0, 0), "均值滤波", (255, 0, 0), font=font)
    cv2charimg = cv2.cvtColor(np.array(pillowimg), cv2.COLOR_RGB2BGR)
    cv2.imshow("blur", cv2charimg)

# 中值滤波
def medianBlur(source):
    img = cv2.medianBlur(source, 3)
    cv2img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    pillowimg = Image.fromarray(cv2img)
    draw = ImageDraw.Draw(pillowimg)  # 图像上打印
    font = ImageFont.truetype("simhei.ttf", 20, encoding="utf-8")
    draw.text((0, 0), "中值滤波", (255, 0, 0), font=font)
    cv2charimg = cv2.cvtColor(np.array(pillowimg), cv2.COLOR_RGB2BGR)
    cv2.imshow("medianBlur", cv2charimg)

# 方框滤波
def boxFilter(source):
    img = cv2.boxFilter(source, -1, (5, 5), normalize=1)
    cv2img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    pillowimg = Image.fromarray(cv2img)
    draw = ImageDraw.Draw(pillowimg)  # 图像上打印
    font = ImageFont.truetype("simhei.ttf", 20, encoding="utf-8")
    draw.text((0, 0), "方框滤波", (255, 0, 0), font=font)
    cv2charimg = cv2.cvtColor(np.array(pillowimg), cv2.COLOR_RGB2BGR)
    cv2.imshow("boxFilter", cv2charimg)

# 高斯滤波
def GaussianBlur(source):
    img = cv2.GaussianBlur(source, (3, 3), 0)
    cv2img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    pillowimg = Image.fromarray(cv2img)
    draw = ImageDraw.Draw(pillowimg)  # 图像上打印
    font = ImageFont.truetype("simhei.ttf", 20, encoding="utf-8")
    draw.text((0, 0), "高斯滤波", (255, 0, 0), font=font)
    cv2charimg = cv2.cvtColor(np.array(pillowimg), cv2.COLOR_RGB2BGR)
    cv2.imshow("GaussianBlur", cv2charimg)

# 高斯边缘检测
def Gauss(source):
    # 计算图像在 X 方向和 Y 方向上的梯度，然后将这两个梯度结合起来以增强图像的边缘
    sobelX = cv2.Sobel(source, cv2.CV_64F, 1, 0)
    sobelY = cv2.Sobel(source, cv2.CV_64F, 0, 1)
    # 计算 X 方向梯度
    sobelX = np.uint8(np.absolute(sobelX))
    # 计算 Y 方向上计算梯度（即垂直边缘检测）
    sobelY = np.uint8(np.absolute(sobelY))
    # sobelX 和 sobelY 中的梯度值结合起来。由于梯度值已经转换为 8 位无符号整数，按位或操作将对应位置的梯度值相加
    img = cv2.bitwise_or(sobelX, sobelY)
    # 以上处理后，边缘被增强，因为边缘处的梯度值较高
    cv2img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    pillowimg = Image.fromarray(cv2img)
    draw = ImageDraw.Draw(pillowimg)  # 图像上打印
    font = ImageFont.truetype("simhei.ttf", 20, encoding="utf-8")
    draw.text((0, 0), "高斯边缘检测", "green", font=font)
    cv2charimg = cv2.cvtColor(np.array(pillowimg), cv2.COLOR_RGB2BGR)
    cv2.imshow("GaussianBlur", cv2charimg)

# 加载图像
img = cv2.imread("../images/dog3.jpg")
cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE)
cv2.imshow("input image", img)
blur(img)
medianBlur(img)
GaussianBlur(img)
# Gaussian(img)  # 这行被注释掉了
cv2.waitKey(0)
cv2.destroyAllWindows()